package com.mvd.app.ac2019;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.mvd.app.R;
import com.mvd.app.activity.BaseActivity;
import com.mvd.app.api.ApiConfig;
import com.mvd.app.application.BaseApplication;
import com.mvd.app.application.MessageEvent;
import com.mvd.app.commons.CommonUtils;
import com.mvd.app.commons.DateUtil;
import com.mvd.app.commons.PDALogUtils;
import com.mvd.app.commons.SharedPreferencesUtils;
import com.mvd.app.commons.UtilsLog;
import com.mvd.app.model.CarsInforModel;
import com.mvd.app.upload.Util;
import com.mvd.app.video.MediaUtils;
import com.mvd.app.video.SendView;
import com.mvd.app.video.VideoProgressBar;
import com.orhanobut.logger.Logger;
import com.vincent.videocompressor.VideoCompress;
import com.zolad.videoslimmer.VideoSlimmer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


public class VideoRecorderActivity extends BaseActivity implements ApiConfig, View.OnClickListener {

    private MediaUtils mediaUtils;
    private boolean isCancel;
    private VideoProgressBar progressBar;
    private int mProgress;
    private TextView btnInfo, btn;
    private TextView view;
    private SendView send;
    private RelativeLayout recordLayout, switchLayout;


    private VideoRecorderActivity instances = null;
    private CarsInforModel carsInforModel;
    private String waijian_chedao = null;//外检车道，检测线代号
    private String video_type, item_code;
    private String Video_start_time = "", Video_End_time = "";//录像开始时间，结束时间
    private String Line = "1";//外检车道
    private boolean IsStarVidep = false;//是否开启录像
    private String isYasuoPhoto;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题栏
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//隐藏状态栏

        setContentView(R.layout.activity_video);
        EventBus.getDefault().register(this);
        instances = this;
        isYasuoPhoto = SharedPreferencesUtils.getIsYasuoPhoto(instances);
        waijian_chedao = getIntent().getExtras().
                getString("CarDetailsActivity_acCarDetailsWaijianchedao", "");
        carsInforModel = (CarsInforModel) getIntent().getSerializableExtra
                ("CarDetailsActivity_CarsInforModel");
        video_type = getIntent().getExtras().getString("video_type", "1");
        item_code = getIntent().getExtras().getString("item_code", "1");
        Logger.e("video_type===" + video_type);
        Line = getIntent().getStringExtra("CarDetailsActivity_Line");
        Logger.e("Line===" + Line);
        String logStrf = "\n" + "onCreate-----绕车一周-----" + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrf.getBytes());
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.main_surface_view);
        // setting
        mediaUtils = new MediaUtils(this);
        mediaUtils.setRecorderType(MediaUtils.MEDIA_VIDEO);
        mediaUtils.setTargetDir(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES));

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
//        mediaUtils.setTargetName(UUID.randomUUID() + ".mp4");
        Logger.e("timeStamp===" + timeStamp);
        mediaUtils.setTargetName(timeStamp + ".mp4");
        mediaUtils.setSurfaceView(surfaceView);

        // btn
        send = (SendView) findViewById(R.id.view_send);
//        view = (TextView) findViewById(R.id.view);
        btnInfo = (TextView) findViewById(R.id.tv_info);
        btn = (TextView) findViewById(R.id.main_press_control);
//        btn.setOnTouchListener(btnTouch);
        btn.setOnClickListener(btnPhotoClick);

        findViewById(R.id.btn_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaUtils != null) {
                    mediaUtils.stopRecordUnSave();
                }
                finish();
            }
        });
        send.backLayout.setOnClickListener(backClick);
        send.selectLayout.setOnClickListener(selectClick);
        recordLayout = (RelativeLayout) findViewById(R.id.record_layout);
        switchLayout = (RelativeLayout) findViewById(R.id.btn_switch);
        switchLayout.setOnClickListener(this);
        progressBar = (VideoProgressBar) findViewById(R.id.main_progress_bar);
        progressBar.setOnProgressEndListener(listener);
        progressBar.setCancel(true);
        XXPermissions.with(this)
                .permission(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean all) {
                        String logStrf = "";

                        if (all) {
                            Logger.e("XXPermissions===" + all);
                            logStrf = "\n" + "获取权限成功==" + "\n" + "all::" + all + "\n";
//                            Toast.makeText(instances, "获取权限成功", Toast.LENGTH_SHORT).show();
//                            try2StartScreenShot();
                        } else {
                            logStrf = "\n" + "获取权限成功，部分权限未正常授予" + "\n";
                            Toast.makeText(instances, "获取权限成功，部分权限未正常授予", Toast.LENGTH_SHORT).show();
                        }
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrf.getBytes());
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {

                    }
                });

    }

    @Override
    protected void onResume() {
        super.onResume();
        // 全屏展示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                // 全屏显示，隐藏状态栏和导航栏，拉出状态栏和导航栏显示一会儿后消失。
                getWindow().getDecorView().setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
            } else {
                // 全屏显示，隐藏状态栏
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
            }
        }
        progressBar.setCancel(true);
    }


    View.OnClickListener btnPhotoClick = new View.OnClickListener() {
        boolean ret = false;
        float downY = 0;

        @Override
        public void onClick(View v) {
            if (IsStarVidep) {
                //正在录像，录像进行中
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, "正在录像，录像进行中".getBytes());
                Video_End_time = DateUtil.currentTime2();
                if (!isCancel) {
                    UtilsLog.e("mProgress===" + mProgress);
                    String logStrf = "\n" + "录像---时间太短不保存" +
                            "\n" + "mProgress::" + mProgress + "\n";
                    PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrf.getBytes());
                    if (mProgress == 0) {
                        stopView(false);
                    }
//                    if (mProgress < 10) {
                    if (mProgress < 2) {
                        //时间太短不保存
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mediaUtils.stopRecordUnSave();
//                                    Toast.makeText(VideoRecorderActivity.this, "时间太短", Toast.LENGTH_SHORT).show();
                                stopView(true);
                            }
                        }, 1300);//后执行Runnable中的run方法
                    }
                    //停止录制
                    mediaUtils.stopRecordSave();
                    stopView(true);
                } else {
                    //现在是取消状态,不保存
                    mediaUtils.stopRecordUnSave();
                    Toast.makeText(VideoRecorderActivity.this, "取消保存", Toast.LENGTH_SHORT).show();
                    stopView(false);
                }
                ret = false;
            } else {
                //点击开始录像
                String logStrf = "\n" + "录像---点击开始录像" + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrf.getBytes());
                mediaUtils.record();
                startView();
                ret = true;
                Video_start_time = DateUtil.currentTime2();
            }
            IsStarVidep = !IsStarVidep;
        }
    };


    VideoProgressBar.OnProgressEndListener listener = new VideoProgressBar.OnProgressEndListener() {
        @Override
        public void onProgressEndListener() {
            progressBar.setCancel(true);
            mediaUtils.stopRecordSave();
        }
    };

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    progressBar.setProgress(mProgress);
                    if (mediaUtils.isRecording()) {
                        mProgress = mProgress + 1;
                        sendMessageDelayed(handler.obtainMessage(0), 1000);
                    }
                    break;
            }
        }
    };

    private void startView() {
        startAnim();
        mProgress = 0;
        handler.removeMessages(0);
        handler.sendMessage(handler.obtainMessage(0));
    }

    private void stopView(boolean isSave) {
        stopAnim();
        progressBar.setCancel(true);
        mProgress = 0;
        handler.removeMessages(0);
        btnInfo.setText("双击放大");
        if (isSave) {
            recordLayout.setVisibility(View.GONE);
            send.startAnim();
        }
    }

    private void startAnim() {
        AnimatorSet set = new AnimatorSet();
        set.playTogether(
                ObjectAnimator.ofFloat(btn, "scaleX", 1, 0.7f),
                ObjectAnimator.ofFloat(btn, "scaleY", 1, 0.7f),
                ObjectAnimator.ofFloat(progressBar, "scaleX", 1, 1.3f),
                ObjectAnimator.ofFloat(progressBar, "scaleY", 1, 1.3f)
        );
        set.setDuration(250).start();
    }

    private void stopAnim() {
        AnimatorSet set = new AnimatorSet();
        set.playTogether(
                ObjectAnimator.ofFloat(btn, "scaleX", 0.5f, 1f),
                ObjectAnimator.ofFloat(btn, "scaleY", 0.5f, 1f),
                ObjectAnimator.ofFloat(progressBar, "scaleX", 1.3f, 1f),
                ObjectAnimator.ofFloat(progressBar, "scaleY", 1.3f, 1f)
        );
        set.setDuration(250).start();
    }

    private View.OnClickListener backClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            send.stopAnim();
            recordLayout.setVisibility(View.VISIBLE);
            mediaUtils.deleteTargetFile();
        }
    };

    private View.OnClickListener selectClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mediaUtils != null) {
                String path = mediaUtils.getTargetFilePath();
                Logger.e("视频保存路径===" + path);
                String logStr1 = "\n" + " 视频保存路径==" + "\n" + path + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr1.getBytes());
                send.stopAnim();
                recordLayout.setVisibility(View.VISIBLE);
                String compressPath = compressVideoPath(path);
                if (CommonUtils.isOnline(instances)) {
                    try {
                        File file = new File(path);
                        if (!TextUtils.isEmpty(Video_start_time)) {

                        } else {
                            Video_start_time = DateUtil.currentTime2();
                        }
                        if (!TextUtils.isEmpty(Video_End_time)) {

                        } else {
                            Video_End_time = DateUtil.currentTime2();
                        }
                        CommonUtils.showLoadingDialog(instances, "加载中...");
//                        videoCompress(path, compressPath);
                        videoCompress_low(path, compressPath);
//                        getDataUploadVideo(file);
                    } catch (Exception e) {
                        String logStr = "\n" + " 上传视频--error" + "\n" + e.getCause()
                                + "\n" + e.getMessage() + "\n" + e.toString() + "\n";
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                    }
                } else {
                    Toast.makeText(instances, getResources().getString(R.string.network_error), Toast
                            .LENGTH_LONG).show();
                }
            }
        }
    };

    String compressVideoPath(String videoUriString) {
        String timeStamp = String.valueOf(System.currentTimeMillis());
        String compressFilePath = "";
//          filePath = Environment.getExternalStorageDirectory().getPath() + "/myvideo/" + timeStamp+".mp4";

//        String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)+ "/compress/";
        String filePath = Environment.getExternalStorageDirectory() + "/compress/";
//        String filePath = Environment.getExternalStorageDirectory() + "/myvideo/compress/";
//        String filePath = Environment.getExternalStorageDirectory() + "/myvideo";
        File mediaStorageDir = new File(filePath);
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                UtilsLog.e("compressVideo--视频路径-compress-文件夹创建失败");
                String logStr22 = "\n" + "compressVideo--视频路径--文件夹创建失败-compress--" + "\n" + filePath + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr22.getBytes());
            }
        }
        compressFilePath = filePath + timeStamp + ".mp4";
        UtilsLog.e("compressVideo--视频路径=videoPath=compress=" + compressFilePath);
        String logStr22 = "\n" + "compressVideo--视频路径=videoPath=compress=" + "\n" + compressFilePath + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr22.getBytes());
        return compressFilePath;
    }

    private long startTime, endTime;

    void videoCompress_low(String videoUriString, String videoPath) {
//        String destPath = tv_output.getText().toString() + File.separator + "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss", getLocale()).format(new Date()) + ".mp4";
        VideoCompress.compressVideoLow(videoUriString, videoPath, new VideoCompress.CompressListener() {
            @Override
            public void onStart() {
                String str = "Compressing..." + "\n"
                        + "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date())
                        + "\n";
                UtilsLog.e("onStart==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                startTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
            }

            @Override
            public void onSuccess() {
                String str = "\n"
                        + "Compress Success!" + "\n"
                        + "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n";
                UtilsLog.e("onSuccess==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                endTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
                Util.writeFile(BaseApplication.getSelf(), "Total: " + ((endTime - startTime) / 1000) + "s" + "\n");
                Util.writeFile(BaseApplication.getSelf());
//                getDataUploadVideo(model, true, "");
                try {
                    File file = new File(videoPath);
                    getDataUploadVideo(file);
                } catch (Exception e) {
                    CommonUtils.hideLoadingDialog(instances);
                    UtilsLog.e("VideoRecorderActivity--videoCompress---e.getMessage()==" + e.getMessage());
                    String logStr = "\n" + " 上传视频--error" + "\n" + e.getCause()
                            + "\n" + e.getMessage() + "\n" + e.toString() + "\n";
                    PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                }
            }

            @Override
            public void onFail() {
                UtilsLog.e("onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
                String str = "onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date());
                endTime = System.currentTimeMillis();
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                Util.writeFile(BaseApplication.getSelf(), "Failed Compress!!!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
            }

            @Override
            public void onProgress(float percent) {
                String str = "视频上传进度==" + String.valueOf(percent) + "%" + "\n" + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                UtilsLog.e("onProgress====" + str);
//                EventBus.getDefault().post(model);
            }
        });
    }

    private Locale getLocale() {
        Configuration config = getResources().getConfiguration();
        Locale sysLocale = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            sysLocale = getSystemLocale(config);
        } else {
            sysLocale = getSystemLocaleLegacy(config);
        }

        return sysLocale;
    }

    @SuppressWarnings("deprecation")
    public static Locale getSystemLocaleLegacy(Configuration config) {
        return config.locale;
    }

    @TargetApi(Build.VERSION_CODES.N)
    public static Locale getSystemLocale(Configuration config) {
        return config.getLocales().get(0);
    }

    void videoCompress(String videoUriString, String videoPath) {
        VideoSlimmer.convertVideo(videoUriString, videoPath, 800, 800, 200 * 360 * 60, new VideoSlimmer.ProgressListener() {
            @Override
            public void onStart() {
                UtilsLog.e("VideoRecorderActivity--videoCompress---视频路径=onStart=");
            }

            @Override
            public void onFinish(boolean result) {
                UtilsLog.e("VideoRecorderActivity--videoCompress---视频路径=onFinish=" + result);
//                //convert finish,result(true is success,false is fail)
                String logStrqw = "\n" + "VideoRecorderActivity-----外检上传视频--videoCompress--onFinish--" +
                        "\n" + "result:" + result + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrqw.getBytes());
                if (result) {
//                    getDataUploadVideo(model, true, "");
                    try {
                        File file = new File(videoPath);
                        getDataUploadVideo(file);
                    } catch (Exception e) {
                        CommonUtils.hideLoadingDialog(instances);
                        UtilsLog.e("VideoRecorderActivity--videoCompress---e.getMessage()==" + e.getMessage());
                        String logStr = "\n" + " 上传视频--error" + "\n" + e.getCause()
                                + "\n" + e.getMessage() + "\n" + e.toString() + "\n";
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                    }

//                    getDataUploadVideo(file);
                }
            }

            @Override
            public void onProgress(float percent) {
                UtilsLog.e("VideoRecorderActivity--videoCompress---视频路径=onProgress=" + percent);
                String logStrqw = "\n" + "VideoRecorderActivity-----外检上传视频--videoCompress--onProgress--" +
                        "\n" + "percent:" + String.valueOf(percent) + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrqw.getBytes());
            }
        });
    }

    //上传视频
    private void getDataUploadVideo(final File file) {
        Logger.e("上传视频---url==" + SharedPreferencesUtils.getFileIP(instances) + UPLOAD_VIDEO);
        OkGo.<String>post(SharedPreferencesUtils.getFileIP(instances) + UPLOAD_VIDEO).tag(instances)
                //次数
                .params("Times", carsInforModel.getTimes())
                //PlatformSN
                .params("PlatformSN", carsInforModel.getPlatformSN())
                .params("VideoType", "PDAVIN")
                .params("ItemCode", "PDA")
                //车牌号码，两个拼起来的
                .params("CarNO", carsInforModel.getPlateRegion() + carsInforModel.getPlateNO())
                //号牌类型
                .params("PlateType", carsInforModel.getPlateType())
                //外检车道，检测线代号
                .params("Line", waijian_chedao)
                //车辆识别代码
                .params("VIN", carsInforModel.getVIN())
                //照片
                .params("zp", file)
                //开始时间
                .params("StartTime", Video_start_time)
                //结束时间
                .params("EndTime", Video_End_time)
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
//                        CommonUtils.showLoadingDialog(instances, "加载中...");
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        Logger.e("上传视频-result==" + result);
                        String logStr = "\n" + "外检上传视频--请求成功" +
                                "\n" + "URL::" + SharedPreferencesUtils.getFileIP(instances) +
                                UPLOAD_VIDEO + "\n" + "result:" + response.body();
                        PDALogUtils.createLogFile(20, logStr.getBytes());
                        if (!TextUtils.isEmpty(result) && !"[[]]".equals(result) && !"[{}]".equals(result)
                                && !"[]".equals(result)) {
                            String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\",
                                    "");
                            Logger.e("上传视频-newResult==" + newResult);
                            if ("ok".equalsIgnoreCase(newResult)) {
                                Intent i = new Intent();
                                Bundle bundle = new Bundle();
                                bundle.putString("result", "1");
                                setResult(666, i.putExtras(bundle));
                                finish();
                                Toast.makeText(instances, "上传录像成功", Toast.LENGTH_LONG).show();
                            } else {
                                String logStr2 = "\n" + "外检上传视频--失败" +
                                        "\n" + "URL::" + SharedPreferencesUtils.getFileIP(instances) +
                                        UPLOAD_VIDEO + "\n" + "result:" + response.body();
                                PDALogUtils.createLogFile(20, logStr2.getBytes());
                                Toast.makeText(instances, "上传录像失败，请重新拍摄", Toast.LENGTH_LONG).show();
                            }
                        } else {
                            String logStr3 = "\n" + "上传视频--失败" +
                                    "\n" + "data::" + "没有数据" + "\n" + "result:" + response.body();
                            PDALogUtils.createLogFile(20, logStr3.getBytes());
                            Logger.e("上传视频-result==" + "没有数据");
                        }
                        CommonUtils.hideLoadingDialog(instances);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Logger.e("上传视频-onError==" + response.body());
                        Logger.e("上传视频-onError==" + response.getException());
                        String logStr = "\n" + "上传录像视频-onError-失败" +
                                "\n" + "URL::" + SharedPreferencesUtils.getFileIP(instances) +
                                UPLOAD_VIDEO + "\n" + "result:" + response.body() + "\n" +
                                response.getException() + "\n" + response.message();
                        PDALogUtils.createLogFile(20, logStr.getBytes());
                        CommonUtils.hideLoadingDialog(instances);
                        Toast.makeText(instances, "上传录像失败，请重试", Toast.LENGTH_LONG).show();
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
        instances = null;
        if (mediaUtils != null) {
            mediaUtils.stopRecordSave();
        }
        EventBus.getDefault().unregister(this);
    }


    private void getData(File file, String file_name) {
        if (!TextUtils.isEmpty(SharedPreferencesUtils.getIP(instances))) {
            if (CommonUtils.isOnline(instances)) {
                getDataUploadPhoto(file);
            } else {
                Toast.makeText(instances, getResources().getString(R.string.network_error), Toast
                        .LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(this, "请设置IP与端口号", Toast.LENGTH_LONG).show();
        }
    }

    //上传照片
    private void getDataUploadPhoto(final File file) {
        Log.e("photo", "6666666");
        Logger.e("getDataUploadPhoto---url==" + SharedPreferencesUtils.getFileIP(instances) + UPLOAD_PHOTO);
        OkGo.<String>post(SharedPreferencesUtils.getFileIP(instances) + UPLOAD_PHOTO).tag(instances)
//                .params("PHOTO_TYPE", PHOTO_TYPE)
                //guid
                .params("QueueID", carsInforModel.getQueueID())
                //guid
                .params("GUID", carsInforModel.getGUID())
                //次数
                .params("Times", carsInforModel.getTimes())
                //PlatformSN
                .params("PlatformSN", carsInforModel.getPlatformSN())
                //SN
                .params("SN", carsInforModel.getSN())
                //拍摄时间
                .params("PhotoDate", DateUtil.currentTime2())
                //照片类型-拍的哪里的照片，位置
//                .params("PhotoType", getPlatformCode(PHOTO_TYPE))
                .params("PhotoType", "0113")
                //车辆类型
                .params("Type", carsInforModel.getType())
                //车牌号码，两个拼起来的
                .params("CarNO", carsInforModel.getPlateRegion() + carsInforModel.getPlateNO())
                //号牌类型
                .params("PlateType", carsInforModel.getPlateType())
                //拍照code F1表示外检
                .params("ItemCode", "F1")
                //外检车道，检测线代号
                .params("Line", Line)
                //车辆识别代码
                .params("VIN", carsInforModel.getVIN())
                .params("FileType", "jpg")
//                .params("FileType", FileUtils.getExtensionName(file.getName()))
                //照片
                .params("zp", file)
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        CommonUtils.showLoadingDialog(instances, "加载中...");

                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        Logger.e("getDataUploadPhoto-result==" + result);
                        String logStr = "\n" + "外检上传照片--请求成功" +
                                "\n" + "URL::" + SharedPreferencesUtils.getFileIP(instances) +
                                UPLOAD_PHOTO + "\n" + "result:" + response.body();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        if (!TextUtils.isEmpty(result) && !"[[]]".equals(result) && !"[{}]".equals(result)
                                && !"[]".equals(result)) {
                            String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\", "");
                            Logger.e("getDataUploadPhoto-newResult==" + newResult);
                            if ("ok".equalsIgnoreCase(newResult)) {
                                Toast.makeText(instances, "上传照片成功", Toast.LENGTH_LONG).show();
                            } else {
                                String logStr2 = "\n" + "外检上传照片--失败" +
                                        "\n" + "URL::" + SharedPreferencesUtils.getFileIP(instances) +
                                        UPLOAD_PHOTO + "\n" + "result:" + response.body();
                                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr2.getBytes());
                                Toast.makeText(instances, "上传照片失败，请重新尝试", Toast.LENGTH_LONG).show();
                            }
                        } else {
                            String logStr3 = "\n" + "外检上传照片--失败" +
                                    "\n" + "data::" + "没有数据" + "\n" + "result:" + response.body();
                            PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr3.getBytes());
                            Logger.e("getDataUploadPhoto-result==" + "没有数据");
                        }
                        CommonUtils.hideLoadingDialog(instances);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Logger.e("getDataUploadPhoto-onError==" + response.getException());
                        String logStr = "\n" + "外检上传照片-onError-失败" +
                                "\n" + "URL::" + SharedPreferencesUtils.getFileIP(instances) +
                                UPLOAD_PHOTO + "\n" + "result:" + response.body() + "\n" +
                                response.getException() + "\n" + response.message();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        CommonUtils.hideLoadingDialog(instances);
                        Toast.makeText(instances, "上传照片失败，请重试", Toast.LENGTH_LONG).show();
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_switch:
//                if (mediaUtils != null && mediaUtils.getTargetFilePath() != null) {
//                    String path = mediaUtils.getTargetFilePath();
//                   Logger.d("path==" + path);
                boolean is = XXPermissions.isHasPermission(this, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE);
                Logger.e("is****************" + is);
                if (is) {
                    try2StartScreenShot();
                } else {
                    Logger.e("****************");
                }
//                } else {
//                    Toast.makeText(instances, "录像未开始", Toast.LENGTH_LONG).show();
//                }

                break;
        }
    }

    private static int REQUEST_MEDIA_PROJECTION = 0;

    private void try2StartScreenShot() {
        MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == REQUEST_MEDIA_PROJECTION) {
//            if (resultCode == RESULT_OK && data != null) {
//                ScreenShotHelper screenShotHelper = new ScreenShotHelper(instances,
//                        resultCode, data, new ScreenShotHelper.OnScreenShotListener() {
//                    @Override
//                    public void onFinish(Bitmap bitmap) {
//                        Logger.d("截屏成功888888888888888888");
//                        String s = "/storage/emulated/0/screenImages/20200401103339.jpg";
////                        getData(new File(s), s);
//                    }
//                });
//                screenShotHelper.startScreenShot();
//            }
//        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void getFilePathEventBus(MessageEvent event) {
        Logger.d("截图路径=VideoRecorderActivity=" + event.getMessage());
        Logger.d("截图路径=VideoRecorderActivity=" + event.getPath());
        filePath = event.getMessage();
        filePath2 = event.getPath();
        if (event != null) {
//            getDataUploadPhoto(new File(event.getMessage()));
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Message msg = new Message();
//                    msg.obj = event.getMessage();
                    msg.arg1 = 1;
                    handler_main.sendMessage(msg);
                }
            }).start();
        }
    }

    String filePath = "", filePath2 = "";
    private Handler handler_main = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//            Logger.d("filePath==" + filePath);
//            Logger.d("filePath=图片名字=" +
//                    com.mvd.app.commons.FileUtils.getFileNameWithSuffix(filePath));
            if (isYasuoPhoto.equals("是")) {
                Luban.with(instances)
                        .load(new File(filePath))
//                load(new File(filePath))
//                        .ignoreBy(100)
//                        .setTargetDir(filePath2)
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {

                            }

                            @Override
                            public void onSuccess(File file) {
                                Logger.e("压缩成功后调用");
                                Logger.e("Luban--file=getPath=" + file.getPath());
                                Logger.e("Luban--file=getAbsolutePath=" + file.getAbsolutePath());
                                Logger.e("Luban--file=getName=" + file.getName());
                                Logger.e("Luban--file=getParent=" + file.getParent());
                                getData(file, filePath);
                            }

                            @Override
                            public void onError(Throwable e) {
                                Logger.e("压缩过程出现问题==" + e.getMessage());
                                Toast.makeText(instances, "图片压缩出现问题，请重试", Toast.LENGTH_LONG).show();
                            }
                        }).launch();
            } else {
                getData(new File(filePath), filePath);
            }

        }
    };


    /**
     * 需要拦截press的事件
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent i = new Intent();
            Bundle bundle = new Bundle();
            bundle.putString("result", "123");
            setResult(666, i.putExtras(bundle));
            finish();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

}